<?php
// 温度数据API接口
// 接收时间戳和温度数据，插入到MySQL数据库

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// 引入数据库配置
require_once 'config.php';

// 只处理POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => '只允许POST请求']);
    exit;
}

// 获取POST数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// 检查数据格式
if (!$data || !isset($data['timestamp']) || !isset($data['temperature'])) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => '缺少必要参数: timestamp 和 temperature']);
    exit;
}

$timestamp = $data['timestamp'];
$temperature = $data['temperature'];

// 获取新参数（如果存在）
$devid = isset($data['devid']) ? $data['devid'] : null;
$devmac = isset($data['devmac']) ? $data['devmac'] : null;
$token = isset($data['token']) ? $data['token'] : null;
$param1 = isset($data['param1']) ? $data['param1'] : null;
$param2 = isset($data['param2']) ? $data['param2'] : null;
$param3 = isset($data['param3']) ? $data['param3'] : null;
$param4 = isset($data['param4']) ? $data['param4'] : null;
$param5 = isset($data['param5']) ? $data['param5'] : null;

// 验证数据
if (!is_numeric($timestamp) || !is_numeric($temperature)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'timestamp 和 temperature 必须是数字']);
    exit;
}

try {
    // 获取数据库连接
    $pdo = getDBConnection();
    
    // 插入数据
    $stmt = $pdo->prepare("INSERT INTO temperature_data (timestamp, temperature, devid, devmac, token, param1, param2, param3, param4, param5) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$timestamp, $temperature, $devid, $devmac, $token, $param1, $param2, $param3, $param4, $param5]);
    
    // 返回成功响应
    echo json_encode([
        'status' => 'success',
        'message' => '数据插入成功',
        'data' => [
            'id' => $pdo->lastInsertId(),
            'timestamp' => $timestamp,
            'temperature' => $temperature,
            'devid' => $devid,
            'devmac' => $devmac,
            'token' => $token,
            'param1' => $param1,
            'param2' => $param2,
            'param3' => $param3,
            'param4' => $param4,
            'param5' => $param5
        ]
    ]);
    
} catch (Exception $e) {
    // 错误处理
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '数据库操作失败: ' . $e->getMessage()]);
}
?>